package com.service;

import cn.hutool.core.util.RandomUtil;
import com.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param mail
     */
    @Override
    public void sendMail(String mail) {
        //产出验证码，并保存到reids
        String code= RandomUtil.randomString(4);

        redisTemplate.boundValueOps(mail).set(code);
        redisTemplate.boundValueOps(mail).expire(30, TimeUnit.MINUTES.MINUTES);

        //发送邮件
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from); //发送者

        message.setTo(mail);
        message.setSubject("验证码注册");  //标题，主题

        message.setText("您的验证码是:"+code);

        javaMailSender.send(message);

    }

    @Override
    public boolean checkCode(String mail, String code) {
        //从redis取出验证码
        String redisCode=(String)redisTemplate.boundValueOps(mail).get();
        System.out.println("redisCode："+redisCode+";code:"+code+";mail:"+mail);

        //验证码是否正确
        boolean f=(code!=null && code.equalsIgnoreCase(redisCode));
        System.out.println("f:"+f);
        if (f){
            //成功后删除原来的
            redisTemplate.boundValueOps(mail).expire(0,TimeUnit.MILLISECONDS);
        }

        return f;

    }
}
